package com.ruoyi.site.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.site.domain.Carts;
import com.ruoyi.site.service.ICartsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;

import static com.ruoyi.common.utils.ServletUtils.getRequest;

/**
 * 购物车Controller
 * * @author chuckeytang
 * @date 2025-10-13
 */
@RestController
@RequestMapping("/site/carts")
public class CartsController extends BaseController
{
    @Autowired
    private ICartsService cartsService;

    @Autowired(required = false) // 假设 TokenService 用于获取当前用户
    private TokenService tokenService;

    /**
     * 查询购物车列表 (后台管理接口)
     */
    @PreAuthorize("@ss.hasPermi('site:carts:list')")
    @GetMapping("/list")
    public TableDataInfo list(Carts carts)
    {
        startPage();
        List<Carts> list = cartsService.selectCartsList(carts);
        return getDataTable(list);
    }

    /**
     * 查询当前用户的购物车详情 (前台用户接口)
     */
    @GetMapping("/user/current")
    public AjaxResult getUserCart()
    {
        // 1. 获取当前登录用户ID
        Long currentUserId = null;
        try {
            LoginUser loginUser = tokenService.getLoginUser(getRequest());
            if (loginUser != null) {
                // 假设这里的 userId 是前台 users 表中的 ID
                currentUserId = loginUser.getUserId();
            }
        } catch (Exception e) {
            return AjaxResult.error("用户未登录或会话无效");
        }

        if (currentUserId == null) {
            return AjaxResult.error("用户ID解析失败，请重新登录");
        }

        // 2. 查询并返回购物车信息（包含所有项目）
        Carts cart = cartsService.selectCartsByUserId(currentUserId);

        if (cart == null) {
            // 如果用户没有购物车，可以考虑在这里为用户创建一个空购物车
            Carts newCart = new Carts();
            newCart.setUserId(currentUserId);
            cartsService.insertCarts(newCart);
            return success(newCart);
        }

        return success(cart);
    }

    /**
     * 导出购物车列表
     */
    @PreAuthorize("@ss.hasPermi('site:carts:export')")
    @Log(title = "购物车", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Carts carts)
    {
        List<Carts> list = cartsService.selectCartsList(carts);
        ExcelUtil<Carts> util = new ExcelUtil<Carts>(Carts.class);
        util.exportExcel(response, list, "购物车数据");
    }

    /**
     * 获取购物车详细信息
     */
    @PreAuthorize("@ss.hasPermi('site:carts:query')")
    @GetMapping(value = "/{cartId}")
    public AjaxResult getInfo(@PathVariable("cartId") Long cartId)
    {
        return success(cartsService.selectCartsByCartId(cartId));
    }

    /**
     * 新增购物车 (通常由系统自动创建，此处为后台管理保留)
     */
    @PreAuthorize("@ss.hasPermi('site:carts:add')")
    @Log(title = "购物车", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Carts carts)
    {
        return toAjax(cartsService.insertCarts(carts));
    }

    /**
     * 修改购物车
     */
    @PreAuthorize("@ss.hasPermi('site:carts:edit')")
    @Log(title = "购物车", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Carts carts)
    {
        return toAjax(cartsService.updateCarts(carts));
    }

    /**
     * 删除购物车
     */
    @PreAuthorize("@ss.hasPermi('site:carts:remove')")
    @Log(title = "购物车", businessType = BusinessType.DELETE)
    @DeleteMapping("/{cartIds}")
    public AjaxResult remove(@PathVariable Long[] cartIds)
    {
        return toAjax(cartsService.deleteCartsByCartIds(cartIds));
    }
}